package lab_2;

import javax.jms.MessageListener;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageFormatException;

/**
 *
 * @author grp02 - Pascal Charreix and Meike Paetz
 *
 * The ServiceOperatorListener class which implements the MessageListener, 
 * represents the Message Listener for service operations.
 */
public class ServiceOperatorListener implements MessageListener {

    private boolean reserving;

    /**
     *
     * ServiceOperatorListener Constructor
     */
    public ServiceOperatorListener() {
        reserving = false;
    }

    /**
     * 
     * Casts an incoming message to either a TextMessage or a MapMessage.
     * This will be displayed.
     */
    public void onMessage(Message m) {
        try {
            if (m instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) m;
                if (textMessage.getText().equals("Package reserved") && reserving == false) {
                    System.out.println("Reserving package...");
                    reserving = true;
                }
                else if (textMessage.getText().equals("Package paid") && reserving == true)
                {
                    System.out.println("Package paid...");
                    reserving = false;
                }
            } else if (m instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) m;
                if (reserving == false) {
                    System.out.println("Information about the Packages :"
                            + "\nHolidayPackageID : " + String.valueOf(mapMessage.getInt("HolidayPackageID"))
                            + "\nCustomerName : " + mapMessage.getString("CustomerName")
                            + "\nPrice : " + String.valueOf(mapMessage.getFloat("Paid"))
                            + "\n\tPaid !");
                } else {
                    System.out.println("Information about the Packages :"
                            + "\nHolidayPackageID : " + String.valueOf(mapMessage.getInt("HolidayPackageID"))
                            + "\nDueDate : " + mapMessage.getString("DueDate")
                            + "\nTravelAgencyName : " + mapMessage.getString("TravelAgencyName")
                            + "\n\tReserved !");
                }
            } else {
                System.err.println("Message is not a TextMessage/ObjectMessage");
            }
        } catch (MessageFormatException e) {
            System.err.println("Object deserialization failed: " + e.toString());
        } catch (JMSException e) {
            System.err.println("JMS exception in onMessage(): " + e.toString());
        } catch (Throwable t) {
            System.err.println("Exception in onMessage():" + t.getMessage());
        }
    }
}
